package com.cyl.manager.ums.controller;

import com.cyl.manager.ums.convert.MemberConvert;
import com.cyl.manager.ums.domain.form.ChangeMemberStatusForm;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.domain.query.MemberQuery;
import com.cyl.manager.ums.domain.vo.MemberDataStatisticsVO;
import com.cyl.manager.ums.domain.vo.MemberOutVO;
import com.cyl.manager.ums.domain.vo.MemberQyVO;
import com.cyl.manager.ums.domain.vo.MemberVO;
import com.cyl.manager.ums.service.MemberService;
import com.cyl.manager.ums.service.MemberTbService;
import com.cyl.wechat.WechatAuthService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 会员信息Controller
 * 
 * @author zcc
 * @date 2022-11-28
 */
@Api(description ="会员信息接口列表")
@RestController
public class MemberController extends BaseController {
    @Autowired
    private MemberService service;
    @Autowired
    private MemberConvert convert;
    @Autowired
    private WechatAuthService wechatAuthService;
    
    @Autowired
    private ISysDeptService deptService;

    
    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private  MemberTbService memberTbService;
    
    @RequestMapping(path ={"/ums/member/wechat/code","/h5/member/wechat/code","/no-auth/wechat/code"},method=RequestMethod.GET)
    public AjaxResult getWechatCode(@RequestParam(required = false) String scene) {
        return AjaxResult.successData(wechatAuthService.getQRCode(scene));
    }

    @ApiOperation("查询会员信息列表")
    @PreAuthorize("@ss.hasPermi('ums:member:list')")
    @PostMapping("/ums/member/list")
    public ResponseEntity<Page<Member>> list(@RequestBody MemberQuery query, Pageable page) {
    	  Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
          if(qrDeptZbjId!=null) {
          	query.setDeptZbjId(qrDeptZbjId);
          }
          if(query.getRolezd()!=null && query.getRolezd().intValue() == -1) {
        	  query.setDeptZbjId(null);
          }
       	Long qxDeptId = SecurityUtils.getQxDeptIdId();
    	if(qxDeptId!=null) {
    		query.setQxDeptId(qxDeptId);
    	}
        List<Member> list = service.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }
    
    @ApiOperation("查询店长信息列表")
    @GetMapping("/ums/member/listDz")
    public ResponseEntity<List<Member>> listDz() {
    	MemberQuery query = new MemberQuery();
    	Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
        if(qrDeptZbjId!=null) {
          	query.setDeptZbjId(qrDeptZbjId);
        }
        return ResponseEntity.ok(service.selectListDzAll(query));
    }

    @ApiOperation("导出会员信息列表")
    @PreAuthorize("@ss.hasPermi('ums:member:export')")
    @Log(title = "会员信息", businessType = BusinessType.EXPORT)
    @GetMapping("/ums/member/export")
    public ResponseEntity<String> export(MemberQuery query) {
    	  Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
          if(qrDeptZbjId!=null) {
          	query.setDeptZbjId(qrDeptZbjId);
          }
          if(query.getRolezd()!=null && query.getRolezd().intValue() == -1) {
        	  query.setDeptZbjId(null);
          }
        List<Member> list = service.selectList(query, null);
        List<MemberOutVO> listOut = new ArrayList<MemberOutVO>();
        Map<Long, SysDept> mapSysDept = new HashMap<Long, SysDept>();
        
        if(list!=null) {
        	for (Member member : list) {
        		Long deptDpId = member.getDeptDpId();
        		SysDept sysDept = null;
        		if(deptDpId!=null) {
        			if(mapSysDept.containsKey(deptDpId)) {
        				sysDept = mapSysDept.get(deptDpId);
        			}else {
        				sysDept = deptService.getCacheSysDept(deptDpId);
        				mapSysDept.put(deptDpId, sysDept);
        			}
        		}
        		listOut.add(new MemberOutVO(member,sysDept));
			}
        }
        ExcelUtil<MemberOutVO> util = new ExcelUtil<MemberOutVO>(MemberOutVO.class);
        return ResponseEntity.ok(util.writeExcel(listOut, "会员信息数据"));
    }

    @ApiOperation("获取会员信息详细信息")
    @PreAuthorize("@ss.hasPermi('ums:member:query')")
    @GetMapping(value = "/ums/member/{id}")
    public ResponseEntity<Member> getInfo(@PathVariable("id") Long id) {
        return ResponseEntity.ok(service.selectById(id));
    }

    @ApiOperation("新增会员信息")
    @PreAuthorize("@ss.hasPermi('ums:member:add')")
    @Log(title = "会员信息", businessType = BusinessType.INSERT)
    @PostMapping("/ums/member")
    public ResponseEntity<Integer> add(@RequestBody Member member) {
        return ResponseEntity.ok(service.insert(member));
    }

    @ApiOperation("修改会员信息")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PutMapping("/ums/member")
    public ResponseEntity<Integer> edit(@RequestBody Member member) {
        return ResponseEntity.ok(service.update(member));
    }
    
    

    @ApiOperation("修改会员状态")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "修改会员状态", businessType = BusinessType.UPDATE)
    @PutMapping("/ums/member/updateHyzt")
    public ResponseEntity<Integer> list(@RequestBody Member query) {
    	Member member = service.selectById(query.getId());
    	if(member==null) {
            throw new RuntimeException("会员id:" +query.getId()+"不存在！");
    	}
    	if(query.getHyzt() == null) {
            throw new RuntimeException("会员状态不能为空");
    	}
    	String memberKey = Constants.MEMBER_INFO+"_"+member.getId();
	    redisCache.deleteObject(memberKey);
    	member.setHyzt(query.getHyzt());
        member.setUpdateTime(LocalDateTime.now());
        return ResponseEntity.ok(service.update(member));
    }
    
    
    
    @ApiOperation("设置为会员角色")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "设置为会员角色", businessType = BusinessType.UPDATE)
    @PutMapping("/ums/member/updateByDz")
    public ResponseEntity<Integer> updateByDz(@RequestBody Member member) {
        return ResponseEntity.ok(service.updateByDz(member.getDeptDpId(),member.getId(),member.getRolezd() ));
    }
    
    
    @ApiOperation("将会员批量迁移到另外一个店长副店长店员")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "将会员批量迁移到另外一个店长副店长店员", businessType = BusinessType.UPDATE)
    @PutMapping("/ums/member/plqy")
    public ResponseEntity<Map<String, Object>> plqy(@RequestBody  MemberQyVO memberQyVO) {
    	 //参数 List<Long> memberIds,Long newMemberId
    	 // memberIds  要迁移的会员列表
    	 // newMemberId  新的 店长 副店长 店员id
        return ResponseEntity.ok(memberTbService.plqy(memberQyVO.getMemberIds(),memberQyVO.getNewMemberId() ));
    }
   
    
    @ApiOperation("群主整体迁移")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "群主整体迁移", businessType = BusinessType.UPDATE)
    @PutMapping("/ums/member/qzztqy")//把群主和群主下的所以会员迁移到兴店铺（群主整体迁移）
    public ResponseEntity<Map<String, Object>> qzztqy(@RequestBody MemberQyVO memberQyVO) {
    	 //参数 Long qzMemberId,Long deptDpId
    	  // qzMemberId 群主id
    	  // deptDpId  新店铺id
        return ResponseEntity.ok(memberTbService.qzztqy(memberQyVO.getQzMemberId(),memberQyVO.getDeptDpId()));
    }
      
    @ApiOperation("设置会员角色")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "设置会员角色", businessType = BusinessType.UPDATE)
    @PutMapping("/ums/member/xghyjs")
    public ResponseEntity<Integer> xghyjs(@RequestBody Member member) {
        return ResponseEntity.ok(memberTbService.xghyjs(member.getId(),member.getRolezd(),member.getSpreaduid()));
    }
    
    	
    
    @ApiOperation("设置店长的其他店铺部门id")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "设置店长的其他店铺部门id", businessType = BusinessType.UPDATE)
    @PutMapping("/ums/member/updateByDzqtDpid")
    public ResponseEntity<Integer> updateByDzqtDpid(@RequestBody Member member) {
        return ResponseEntity.ok(service.updateByDzqtDpid(member.getId(),member.getQtDeptDpIds()));
    }
    


    @ApiOperation("修改会员备注信息")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "会员备注信息", businessType = BusinessType.UPDATE)
    @PostMapping("/ums/member/mark/update")
    public ResponseEntity<Integer> editMark(@RequestBody Member member) {
        return ResponseEntity.ok(service.updateMark(member));
    }
    
    @ApiOperation("修改会员spreaduid信息")
    @PreAuthorize("@ss.hasPermi('ums:member:edit')")
    @Log(title = "会员spreaduid信息", businessType = BusinessType.UPDATE)
    @PostMapping("/ums/member/spreaduid/update")
    public ResponseEntity<Integer> editSpreaduid(@RequestBody Member member) {
        return ResponseEntity.ok(service.updateSpreaduid(member));
    }


    @ApiOperation("删除会员信息")
    @PreAuthorize("@ss.hasPermi('ums:member:remove')")
    @Log(title = "会员信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/ums/member/{id}")
    public ResponseEntity<Integer> remove(@PathVariable Long id) {
        return ResponseEntity.ok(service.deleteById(id));
    }

    @ApiOperation(("修改会员账户状态"))
    @Log(title = "会员信息", businessType = BusinessType.UPDATE)
    @PostMapping("/ums/member/status/change")
    public ResponseEntity<Integer> changeStatus(@RequestBody ChangeMemberStatusForm form){
        return ResponseEntity.ok(service.changeStatus(form));
    }

    @ApiOperation("会员手机号解密")
    @GetMapping("/ums/member/phone/decrypt/{phoneEncrypted}")
    public ResponseEntity<String> getPhoneDecrypted(@PathVariable String phoneEncrypted){
        return ResponseEntity.ok(service.getPhoneDecrypted(phoneEncrypted));
    }

    @ApiOperation("查看会员统计数据")
    @GetMapping("/ums/member/view/statistics/{memberId}")
    public ResponseEntity<MemberDataStatisticsVO> viewStatistics(@PathVariable Long memberId){
        return ResponseEntity.ok(service.viewStatistics(memberId));
    }
}
